package com.macro.mall.wx.service.impl;

import com.alibaba.fastjson.JSON;
import com.macro.mall.common.util.HttpClient;
import com.macro.mall.wx.API.WxAPI;
import com.macro.mall.wx.sdk.WxBeanConfig;
import com.macro.mall.wx.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private WxBeanConfig wxBeanConfig;

    @Override
    public String getOpenId(String jsCode) {
        Map<String, String> map = new HashMap<>();
        map.put("appid", wxBeanConfig.getAppId());
        map.put("secret", wxBeanConfig.getSecret());
        map.put("js_code", jsCode);
        map.put("grant_type", "authorization_code");
        String url = WxAPI.JS_CODE_2_SESSION + HttpClient.buildMap(map);
        try {
            String res = HttpClient.get(url);
            System.out.println("getOpenId-----------------" + res);
            if (StringUtils.isNotBlank(res)) {
                Map<String, Object> result = JSON.parseObject(res, Map.class);
                if (result != null && !result.isEmpty()) {
                    String errcode = String.valueOf(result.get("errcode"));
                    if (errcode == null || "0".equals(errcode) || "null".equals(errcode)) {//成功
                        return String.valueOf(result.get("openid"));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
